const systemInfo = {
  windowHeight: wx.getWindowInfo().windowHeight,
  windowWidth: wx.getWindowInfo().windowWidth,
  platform: wx.getAppBaseInfo().platform,
};

Page({
  data: {
    userType: "user", // user, merchant, admin
    username: "",
    password: "",
    rememberPwd: false,
  },

  // 选择用户类型
  selectUserType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      userType: type,
      username: "",
      password: "",
    });
  },

  // 输入用户名
  onUsernameInput(e) {
    this.setData({
      username: e.detail.value,
    });
  },

  // 输入密码
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value,
    });
  },

  // 切换记住密码
  toggleRememberPwd() {
    this.setData({
      rememberPwd: !this.data.rememberPwd,
    });
  },

  // 处理登录
  async handleLogin() {
    switch (this.data.userType) {
      case "merchant":
        await this.handleMerchantLogin();
        break;
      case "admin":
        await this.handleAdminLogin();
        break;
      default:
        await this.handleWechatLogin();
    }
  },

  // 商家登录
  async handleMerchantLogin() {
    let isLoading = false;
    try {
      // 表单验证
      if (!this.data.username || !this.data.password) {
        wx.showToast({
          title: "请输入账号密码",
          icon: "none",
        });
        return;
      }

      isLoading = true;
      wx.showLoading({
        title: "登录中...",
        mask: true,
      });

      console.log("开始调用云函数，参数：", {
        username: this.data.username,
        password: this.data.password,
      });

      const { result } = await wx.cloud.callFunction({
        name: "merchantLogin",
        data: {
          username: this.data.username,
          password: this.data.password,
        },
      });

      console.log("云函数返回结果：", result);

      if (isLoading) {
        wx.hideLoading();
        isLoading = false;
      }

      if (result && result.code === 0) {
        wx.showToast({
          title: "登录成功",
          icon: "success",
        });
        wx.setStorageSync("merchantInfo", result.data);
        setTimeout(() => {
          wx.redirectTo({
            url: "/pages/merchant/index",
          });
        }, 1500);
      } else {
        wx.showToast({
          title: result?.msg || "账号或密码错误",
          icon: "none",
        });
      }
    } catch (err) {
      console.error("登录失败：", err);
      if (isLoading) {
        wx.hideLoading();
        isLoading = false;
      }
      wx.showToast({
        title: "登录失败，请稍后重试",
        icon: "none",
      });
    }
  },

  // 管理员登录
  async handleAdminLogin() {
    // 管理员登录逻辑
  },

  // 微信登录
  async handleWechatLogin() {
    // 微信登录逻辑
  },
});
